/**
 * 节拍器音频文件下载脚本
 * 用于从Pixabay下载节拍器所需的所有音频文件
 */

const fs = require('fs');
const path = require('path');
const https = require('https');
const http = require('http');

// 确保目录存在
const SOUNDS_DIR = path.join(__dirname, 'static', 'sounds');
if (!fs.existsSync(SOUNDS_DIR)) {
  console.log(`创建目录: ${SOUNDS_DIR}`);
  fs.mkdirSync(SOUNDS_DIR, { recursive: true });
}

// Pixabay音频文件链接
const soundFiles = [
  {
    name: 'click_accent.mp3',
    url: 'https://cdn.pixabay.com/download/audio/2022/03/10/audio_99cccd2f80.mp3'
  },
  {
    name: 'click_normal.mp3',
    url: 'https://cdn.pixabay.com/download/audio/2021/08/09/audio_414d8083ac.mp3'
  },
  {
    name: 'woodblock_accent.mp3',
    url: 'https://cdn.pixabay.com/download/audio/2021/07/27/audio_433d7d1269.mp3'
  },
  {
    name: 'woodblock_normal.mp3',
    url: 'https://cdn.pixabay.com/download/audio/2022/01/18/audio_d01e5d6fc7.mp3'
  },
  {
    name: 'drum_accent.mp3',
    url: 'https://cdn.pixabay.com/download/audio/2022/03/15/audio_d0c6ff1c4b.mp3'
  },
  {
    name: 'drum_normal.mp3',
    url: 'https://cdn.pixabay.com/download/audio/2022/01/27/audio_d0bb9f286e.mp3'
  },
  {
    name: 'electronic_accent.mp3',
    url: 'https://cdn.pixabay.com/download/audio/2021/08/04/audio_c8a7303ec2.mp3'
  },
  {
    name: 'electronic_normal.mp3',
    url: 'https://cdn.pixabay.com/download/audio/2021/10/19/audio_1570f267a0.mp3'
  }
];

// 备用链接（其他免费音效网站）
const backupSoundFiles = [
  {
    name: 'click_accent.mp3',
    url: 'https://freesound.org/data/previews/184/184437_2873696-lq.mp3'
  },
  {
    name: 'click_normal.mp3',
    url: 'https://freesound.org/data/previews/184/184438_2873696-lq.mp3'
  },
  {
    name: 'woodblock_accent.mp3',
    url: 'https://freesound.org/data/previews/29/29613_98055-lq.mp3'
  },
  {
    name: 'woodblock_normal.mp3',
    url: 'https://freesound.org/data/previews/29/29614_98055-lq.mp3'
  },
  {
    name: 'drum_accent.mp3',
    url: 'https://freesound.org/data/previews/207/207901_38963-lq.mp3'
  },
  {
    name: 'drum_normal.mp3',
    url: 'https://freesound.org/data/previews/219/219244_4096260-lq.mp3'
  },
  {
    name: 'electronic_accent.mp3',
    url: 'https://freesound.org/data/previews/320/320100_5038597-lq.mp3'
  },
  {
    name: 'electronic_normal.mp3',
    url: 'https://freesound.org/data/previews/216/216563_2574468-lq.mp3'
  }
];

// 下载单个文件的函数
function downloadFile(url, destination) {
  return new Promise((resolve, reject) => {
    const client = url.startsWith('https') ? https : http;
    
    console.log(`开始下载: ${url}`);
    
    const request = client.get(url, (response) => {
      // 检查HTTP状态码
      if (response.statusCode === 200) {
        const file = fs.createWriteStream(destination);
        
        response.pipe(file);
        
        file.on('finish', () => {
          file.close();
          console.log(`✓ 下载成功: ${destination}`);
          resolve(true);
        });
        
        file.on('error', (err) => {
          fs.unlink(destination, () => {}); // 删除部分下载的文件
          console.error(`✗ 文件写入错误: ${err.message}`);
          reject(err);
        });
      } else if (response.statusCode === 301 || response.statusCode === 302) {
        // 处理重定向
        console.log(`→ 重定向至: ${response.headers.location}`);
        downloadFile(response.headers.location, destination)
          .then(resolve)
          .catch(reject);
      } else {
        console.error(`✗ 下载失败 [${response.statusCode}]: ${url}`);
        reject(new Error(`HTTP 状态码: ${response.statusCode}`));
      }
    });
    
    request.on('error', (err) => {
      console.error(`✗ 请求错误: ${err.message}`);
      reject(err);
    });
    
    // 设置超时
    request.setTimeout(30000, () => {
      request.abort();
      console.error(`✗ 请求超时: ${url}`);
      reject(new Error('请求超时'));
    });
  });
}

// 尝试从主源和备用源下载文件
async function downloadWithFallback(file, index) {
  const filePath = path.join(SOUNDS_DIR, file.name);
  
  try {
    console.log(`\n[${index+1}/${soundFiles.length}] 开始下载: ${file.name}`);
    
    // 检查文件是否已存在
    if (fs.existsSync(filePath)) {
      const stats = fs.statSync(filePath);
      if (stats.size > 0) {
        console.log(`✓ 文件已存在，跳过下载: ${file.name}`);
        return true;
      } else {
        console.log(`! 文件存在但为空，重新下载: ${file.name}`);
      }
    }
    
    // 尝试从主源下载
    await downloadFile(file.url, filePath);
    return true;
  } catch (mainError) {
    console.error(`✗ 主源下载失败: ${mainError.message}`);
    console.log(`尝试从备用源下载...`);
    
    // 查找对应的备用链接
    const backupFile = backupSoundFiles.find(bf => bf.name === file.name);
    
    if (backupFile) {
      try {
        await downloadFile(backupFile.url, filePath);
        return true;
      } catch (backupError) {
        console.error(`✗ 备用源也下载失败: ${backupError.message}`);
        return false;
      }
    } else {
      console.error(`✗ 没有找到备用源`);
      return false;
    }
  }
}

// 主函数 - 下载所有音频文件
async function downloadAllSounds() {
  console.log('===== 节拍器音频文件下载工具 =====');
  console.log(`总共需要下载 ${soundFiles.length} 个文件到: ${SOUNDS_DIR}\n`);
  
  let successCount = 0;
  let failCount = 0;
  
  for (let i = 0; i < soundFiles.length; i++) {
    const success = await downloadWithFallback(soundFiles[i], i);
    if (success) {
      successCount++;
    } else {
      failCount++;
    }
  }
  
  console.log('\n===== 下载完成 =====');
  console.log(`成功: ${successCount} 个文件`);
  console.log(`失败: ${failCount} 个文件`);
  
  if (failCount > 0) {
    console.log('\n一些文件下载失败。请检查网络连接，或稍后再试。');
    console.log('您也可以手动下载文件，并将其保存到 static/sounds/ 目录。');
    process.exit(1);
  } else {
    console.log('\n所有文件下载成功！可以开始使用节拍器了。');
  }
}

// 执行下载程序
downloadAllSounds().catch(err => {
  console.error('下载过程中发生错误:', err);
  process.exit(1);
}); 